package com.chixing.controller;

import com.chixing.service.IMinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class uploadFileController {
    @Autowired
    private IMinioService minioService;

    // 上传文件并返回URL和文件名
    @PostMapping("/uploadgeturl")
    public ResponseEntity<Map<String, String>> uploadFileGetURL(@RequestParam("file") MultipartFile file){
       try{
           String objectName = minioService.uploadFile(file);
           // 获取文件URL
           String fileUrl = minioService.getFileUrl(objectName, 60); // 60分钟有效期

           // 创建返回的数据
           Map<String, String> result = new HashMap<>();
           result.put("objectName", objectName);
           result.put("fileUrl", fileUrl);

           return ResponseEntity.ok(result);
       } catch (Exception e) {
           e.printStackTrace();
           Map<String, String> error = new HashMap<>();
           error.put("error", "文件上传失败: " + e.getMessage());
           return ResponseEntity.status(500).body(error);
       }
    }

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file){
        try{
            String objectName = minioService.uploadFile(file);
            return ResponseEntity.ok("文件上传成功,对象名称:" + objectName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("文件上传失败:" + e.getMessage());
        }
    }

    // 获取文件URL
    @GetMapping
    public ResponseEntity<String> getFileUrl(@RequestParam String objectName){
        try{
            String url = minioService.getFileUrl(objectName, 3600);
            return ResponseEntity.ok(url);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获得文件URL失败:" + e.getMessage());
        }
    }

    // 删除文件
    @GetMapping("/delete")
    public ResponseEntity<String> deleteFile(@RequestParam String objectName){
        try{
            minioService.deleteFile(objectName);
            return ResponseEntity.ok("文件删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("文件删除失败:" + e.getMessage());
        }
    }
}
